<template>
  <q-card-section>
    <p class="text-grey-6">管理广告图片的分类，可建立两级分类。</p>
    <q-table
      :data="table.tableContentData"
      :columns="table.columns"
      :visibleColumns="table.visibleColumns"
      row-key="index"
      :loading="table.loading"
      :pagination.sync="table.initialPagination"
      rows-per-page-label="每页显示"
      flat
      bordered
      :separator="table.separator"
      selection="multiple"
      :selected.sync="table.selected"
    >
      <template v-slot:top>
        <div class="col-4">
          <q-select
            outlined
            dense
            v-model="form.model"
            :options="form.options"
            label="一级分类"
            clear-icon="mdi-close"
            clearable
            options-selected-class="text-primary"
            @input="getList(form.model)"
          />
        </div>
        <q-space />
        <div class="col-4">
          <q-btn-group
            flat
            class="float-right"
          >
            <q-btn
              color="negative"
              text-color="white"
              icon="mdi-delete"
              label="批量删除"
              size="md"
              @click="getSelectedRows"
            />
            <q-btn
              color="primary"
              icon="mdi-table-row-plus-after"
              label="添加"
              size="md"
              @click="dialog.addRow = true"
            />
          </q-btn-group>
        </div>
      </template>
      <template v-slot:body-cell-Action="props">
        <q-td :props="props">
          <q-btn-group flat>
            <q-btn
              flat
              icon="mdi-delete"
              label="删除"
              size="sm"
              color="negative"
              @click="getDeleteRow(props.row)"
            />
            <q-btn
              flat
              icon="mdi-table-edit"
              label="编辑"
              size="sm"
              color="primary"
              @click="getEditRow(props.row)"
            />
          </q-btn-group>
        </q-td>
      </template>
      <template v-slot:loading>
        <q-inner-loading
          showing
          color="primary"
        />
      </template>
    </q-table>
    <!-- 对话框-删除确认 -->
    <q-dialog v-model="dialog.delConfirm">
      <q-card>
        <q-card-section class="row items-center">
          <q-avatar
            icon="mdi-alert-circle-outline"
            text-color="negative"
          />
          <span class="q-ml-sm text-negative">确定要删除所选记录吗？</span>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            flat
            label="取消"
            v-close-popup
          />
          <q-btn
            flat
            label="确定删除"
            color="negative"
            v-close-popup
            @click="deleteRows(deleteID)"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <!-- 对话框-编辑 -->
    <q-dialog
      v-model="dialog.editConfirm"
      persistent
      @input="clearDialogForm"
    >
      <q-card style="width:400px">
        <q-card-section>
          <div class="q-pb-md text-h6">编辑分类</div>
          <q-separator />
        </q-card-section>
        <q-card-section class="row items-center">
          <q-form
            class="q-gutter-y-md full-width"
            @submit.prevent.stop="editRow"
          >
            <q-select
              outlined
              dense
              color="primary"
              v-model="dialog.form.model"
              :options="dialog.form.options"
              label="一级分类"
              name="UpColumnID"
            />
            <q-input
              hide-bottom-space
              outlined
              v-model="dialog.form.columnName"
              label="请输入分类名称"
              name="ColumnName"
              :rules="[val => !!val || '此项不能为空']"
            />
            <q-input
              hide-bottom-space
              outlined
              v-model="dialog.form.id"
              label="ID"
              name="ID"
              class="hidden"
            />

            <q-separator />
            <q-card-actions align="right">
              <q-btn
                flat
                label="取消"
                v-close-popup
              />
              <q-btn
                flat
                label="保存"
                color="primary"
                v-close-popup
                type="submit"
              />
            </q-card-actions>

          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>
    <!-- 对话框-添加 -->
    <q-dialog
      v-model="dialog.addRow"
      persistent
      @input="clearDialogForm"
    >
      <q-card style="width:400px">
        <q-card-section>
          <div class="q-pb-md text-h6">添加新分类</div>
          <q-separator />
        </q-card-section>
        <q-card-section class="row items-center">
          <q-form
            class="q-gutter-y-md full-width"
            @submit.prevent.stop="addRow"
          >
            <q-select
              outlined
              dense
              v-model="dialog.form.model"
              :options="dialog.form.options"
              label="一级分类"
              name="UpColumnID"
            />
            <q-input
              hide-bottom-space
              outlined
              v-model="dialog.form.columnName"
              label="请输入分类名称"
              name="ColumnName"
              :rules="[val => !!val || '此项不能为空']"
            />
            <q-separator />
            <q-card-actions align="right">
              <q-btn
                flat
                label="取消"
                v-close-popup
              />
              <q-btn
                flat
                label="添加"
                color="primary"
                v-close-popup
                type="submit"
              />
            </q-card-actions>

          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-card-section>
</template>

<script>
import { mapMutations } from 'vuex'

export default {
  name: 'PageAdCategory',
  components: {
  },
  props: {},
  data () {
    return {
      // ---------- 下拉框
      form: {
        model: null,
        options: [],
        columnName: '',
      },
      // ---------- 表格
      table: {
        // 默认$Api参数
        defaultUpCategory: -1,
        defaultPageIndex: 1,
        // 初始化分页
        initialPagination: {
          sortBy: 'desc',
          descending: false,
          page: 1,
          rowsPerPage: 0,
          current: 1,
          rowsNumber: 0 //if getting data from a server
        },
        // 分割线模式可选值：horizontal (default)', 'vertical', 'cell', 'none'
        separator: 'horizontal',
        loading: true,
        // 可见列
        visibleColumns: ['UpCategoryName', 'CategoryName',  'Action'],
        columns: [
          {
            name: 'index',
            required: true,
            label: '序号',
            align: 'center',
            field: 'index'
          },
          { name: 'UpCategoryName', align: 'left', label: '一级分类', field: 'UpCategoryName' },
          { name: 'UpCategoryID', align: 'left', label: 'UpCategoryID', field: 'UpCategoryID' },
          { name: 'ID', align: 'left', label: 'ID', field: 'ID' },
          { name: 'CategoryName', align: 'left', label: '二级分类', field: 'CategoryName' },
          { name: 'Action', align: 'center', label: '操作', field: '', style: 'min-width:220px' },
        ],
        tableContentData: [],
        selected: []
      },
      // ---------- 对话框
      dialog: {
        delConfirm: false,
        editConfirm: false,
        editData:{},
        addRow: false,
        form: {
          model: {
            icon: '',
            label: '顶级分类',
            value: 0
          },
          options: [],
          UpCategoryName: '',
          id: '',
          columnName: '',
        },
      },
      deleteID: [],
      addRowResult: {},
      editRowResult: {}
    }
  },
  methods: {
    // 获取分类列表内容
    getList(modelValue) {
      const _params = {
        id: this.table.defaultUpCategory
      }
      if (modelValue !== null) {
        _params.id = modelValue.value
      }
      this.$api.AdCategoryParams('GetAdvertList', 'get', _params).then (result => {
        this.table.tableContentData = result
        this.table.initialPagination.rowsNumber = result.length
        this.table.initialPagination.rowsPerPage = result.length
        // 生成序号
        this.table.tableContentData.forEach((row, index) => {
          row.index = index + 1
        })
        // 关闭加载动画
        this.table.loading = false
        // console.log(result) 
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
    },
    // 获取分类过滤数据
    getUpCategory() {
       this.$api.AdCategoryParams('getUpColumn', 'get').then (result => {
        // 格式化获得的数据，更改对象数组的key键名称
        let _result = result.map( item => ({
          UpCategoryID : item.UpColumnID,
          label : item.ColumnName,
          value : item.ID
        }))
        // console.log(_result)
        this.form.options = _result
        this.dialog.form.options = _result
        // console.log(result)
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
    },
    // 获得编辑的行数据
    getEditRow(value) {
      this.dialog.editConfirm = true
      // console.log(value)
      this.dialog.form.model.label = value.UpCategoryName
      this.dialog.form.model.value = value.UpCategoryID
      this.dialog.form.columnName = value.CategoryName
      this.dialog.form.id = value.ID
    },
    // 提交编辑数据
    editRow (evt) {
      this.editRowResult = this.$utils.formatFormData(evt)
      delete this.editRowResult.ID
      // console.log(this.editRowResult)
      
      this.$api.AdCategoryData(this.dialog.form.id, 'put', this.editRowResult).then (result => {
        // console.log(result)
         if ( result === 'success') {
          this.clearDialogForm()
          this.$utils.notify('数据修改成功！', 'positive')
          // 重新请求数据列表
          this.getList(this.form.model)
         } else if ( result === 'error' ) {
           this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
         } else if ( result === 'exist' ) {
           this.$utils.notify('该分类已存在，请更换分类名称', 'red-10')
         }
      }).catch (err => {
        console.log(err)
      })
    },
    // 添加新行
    addRow(evt) {
      this.addRowResult = this.$utils.formatFormData(evt)
      
      this.$api.AdCategoryData('', 'post', this.addRowResult).then (result => {
        // console.log(result)
        if ( result === 'success') {
          this.clearDialogForm()
        //  重新请求数据列表
          this.getList(this.form.model)
        } else if ( result === 'error' ) {
          this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
        } else if ( result === 'exist' ) {
          this.$utils.notify('该分类已存在，请更换分类名称', 'red-10')
        } else {
          this.$utils.notify(result, 'red-10')
        }
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
    },
    // 显示多条选择行数量信息
    selectedRowMessage() {
      return this.table.selected.length === 0 ? '' : `选择了全部${this.table.tableContentData.length}条记录中的${this.table.selected.length} 条`
    },
    // 获取多条选择行ID值数组
    getSelectedRows() {
      this.deleteID = []
      this.table.selected.map((row) => {
        this.deleteID.push( row.ID)
      })
      if (this.table.selected.length > 0) {
        this.dialog.delConfirm = true
      } else {
        this.$utils.notify('请选择要删除的记录','red-8')
      }
    },
    // 获取单条删除的row信息
    getDeleteRow(value) {
      this.deleteID = []
      this.deleteID.push(value.ID)
      this.dialog.delConfirm = true
    },
    // 提交服务器并删除本地信息
    deleteRows(rowid) {
      // 删除脚本
      const _ids =rowid
      this.$api.AdCategoryData('', 'delete', _ids).then (result => {
        // console.log(result)
         if ( result === 'success') {
          //  重新请求数据列表
           this.getList(this.form.model)
           this.getUpCategory()
         } else if ( result === 'error' ) {
           this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
         } else if ( result === 'failure' ) {
           this.$utils.notify('不能删除有下级分类的项目，请先删除或转移下级分类', 'red-8')
         }
      }).catch (err => {
        console.log(err)
      })
      // 删除本地数组中的数据
      // rowid.forEach(item => {
      //   this.table.tableContentData.forEach((row, index) => {
      //     if (row.ID === item) {
      //       this.table.tableContentData.splice(index === 0 ? index : index-1, 1)
      //     }
      //   })
      // })
      this.deleteID = []
      this.table.selected = []
    },
    // 清除表单内容
    clearDialogForm() {
        this.dialog.form.model.icon = ''
        this.dialog.form.model.label = '选择分类'
        this.dialog.form.model.value = 0
        this.dialog.form.columnName = ''
        this.getUpCategory()
    },
    // session过期操作
    ...mapMutations(['changeLogin']),
    unauthorized() {
      // 弹出警告框
      this.$utils.notify('身份信息过期','red-8')
      // 清除vuex中的token
      this.changeLogin({ Authorization: '' })
      // 路由跳转
      this.$router.push('/Login', onComplete => {}, onAbort => {});
    }
  },
  mounted() {
    this.getList(this.form.model)
    this.getUpCategory()
  },
}
</script>
<style>
.q-pagination .q-btn__wrapper:before {
  box-shadow: none;
}
</style>